<?php

$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var
set_time_limit(0);
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

//bind socket to specified host
socket_bind($socket, 0, $port);

//listen to port
socket_listen($socket);
echo "Init server success\n"; 
//create & add listning socket to the list
$clients = array($socket);
$userName = array("server");
$listName = array();
$listColor = array();
$colours = array('007AFF', 'FF7000', 'FF7000', '15E25F', 'CFC700', 'CFC700', 'CF1100', 'CF00BE', 'F00', '#282E33', '#25373A', '#164852', '#495E67', '#FF3838');
$messageBefore = "";

//start endless loop, so that our script doesn't stop
while (true) {
    //manage multipal connections
    $changed = $clients;
    //returns the socket resources in $changed array
    socket_select($changed, $null, $null, 0, 10);

    //check for new socket
    if (in_array($socket, $changed)) {
        $socket_new = socket_accept($socket); //accpet new socket
        $header = socket_read($socket_new, 1024); //read data sent by the socket
        if($header != ""){
            addElement($clients, $socket_new); //add socket to client array
            perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
            $response = mask(json_encode(array('type' => 'connected'))); //prepare json data
            socket_write($socket_new, $response, strlen($response));//send data for new connection
            //make room for new socket
            $found_socket = array_search($socket, $changed);
            unset($changed[$found_socket]);
        }
    }

    //loop through all connected sockets
    foreach ($changed as $changed_socket) {
        $buf = null;
        //check for any incomming data
        $reslut = socket_recv($changed_socket, $buf, 1024, 0);
        if($reslut == 0) 
            clientClose($changed_socket);
        else {
            $received_text = unmask($buf); //unmask data
            $tst_msg = json_decode($received_text); //json decode 
            if($tst_msg != null){
                $user_name = $tst_msg->name; //sender name
                $user_type = $tst_msg->type;
                if($user_type == 'score'){
                    $user_message = $tst_msg->message; //message text
                    $con = mysql_connect("localhost", "root", "");
                    mysql_select_db("ltm", $con);
                    $sql = "select * from bangxephang where username='$user_name' ";
                    $query = mysql_query($sql);
                    $data = mysql_fetch_assoc($query);
                    $point = $data['sodiem'];
                    if ($point < $user_message) {
                        $sql = "update bangxephang set sodiem='$user_message' where username= '$user_name' ";
                        mysql_query($sql);
                    }
                }
                else if ($user_type == 'message') {
                    $user_message = $tst_msg->message; //message text
                    if($user_message != $messageBefore){
                        $messageBefore = $user_message;
                        $user_color = $tst_msg->color; //color
                        $chat_friend = $tst_msg->friend;
                        //prepare data to be sent to client
                        $response_text = mask(json_encode(array('type' => 'usermsg', 'name' => $user_name, 'message' => $user_message, 'color' => $user_color, 'friend' => $chat_friend)));
                        send_message($response_text); //send data
                    }
                }
                else if ($user_type == 'connected') {
                    addElement($userName, $user_name);
                    if(count($clients) > count($userName))
                    {                            
                        $index = count($clients) - 1;
                        socket_close($clients[$index]);
                        deleteElement($clients, $index);
                    }                        
                    echo "\nUser name: $user_name connect.";
                    $len = count($listName);
                    $isName = false;
                    for($i = 0; $i < $len; $i++) {
                        if($user_name == $listName[$i]) {
                            $isName = true;
                            break;
                        }
                    }
                    for($i = 0; $i < $len; $i++)
                    {
                        $response_text = mask(json_encode(array('type' => 'friend', 'name' => $listName[$i])));
                        socket_write ($changed_socket, $response_text,  strlen($response_text));
                    }
                    if($isName == false){
                        addElement($listName, $user_name);
                        addElement($listColor, $colours[array_rand($colours)]); 
                        echo "\nThis is user new.";                      
                    }
                    $index = array_search($user_name, $listName);
                    $colour = $listColor[$index];                    
                    $response = mask(json_encode(array('type' => 'color', 'color' => $colour))); //prepare json data
                    socket_write($changed_socket, $response, strlen($response));//send data for new connection
                    $response_text = mask(json_encode(array('type' => 'friend', 'name' => $user_name)));
                    send_message($response_text); //send data
                }
            }
            break ; //exist this loop
       }
    }
}
// close the listening socket
echo "\nClose socket server";
socket_close($sock);

function clientClose($changed_socket){
    global $clients, $userName, $listName, $listColor;
    // remove client for $clients array
    $found_socket = array_search($changed_socket, $clients);
    if($found_socket != 0){
        $user_name = $userName[$found_socket];   
        echo "\nClient user name: $user_name disconnect.";
        socket_close($clients[$found_socket]);
        deleteElement($clients, $found_socket);
        deleteElement($userName, $found_socket);
        //notify all users about disconnected connection
        $connect = array_search($user_name, $userName);
        if($connect === FALSE){
            $foundName = array_search($user_name, $listName);
            deleteElement($listName, $foundName);
            deleteElement($listColor, $foundName);
            $response = mask(json_encode(array('type' => 'disconnected', 'name' => $user_name)));
            send_message($response);
        }    
    }
}
function addElement(&$array, $value)
{   
    $array[count($array)] = $value;
}
function deleteElement(&$array, $index)
{    
    if($index === FALSE)        
        return;
    $len = count($array);
    for($i = $index; $i < $len - 1; $i++)
    {
        $array[$i] = $array[$i + 1];
    }
    unset($array[$len - 1]);
}
function send_message($msg) {
    global $clients, $userName;
    $len = count($clients);
    for($i = 1;  $i < $len ; $i++) {
        socket_write($clients[$i], $msg, strlen($msg));
    }
    return true;
}

//Unmask incoming framed message
function unmask($text) {
    $length = ord($text[1]) & 127;
    if ($length == 126) {
        $masks = substr($text, 4, 4);
        $data = substr($text, 8);
    } elseif ($length == 127) {
        $masks = substr($text, 10, 4);
        $data = substr($text, 14);
    } else {
        $masks = substr($text, 2, 4);
        $data = substr($text, 6);
    }
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i % 4];
    }
    return $text;
}

//Encode message for transfer to client.
function mask($text) {
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if ($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif ($length > 125 && $length < 65536)
        $header = pack('CCn', $b1, 126, $length);
    elseif ($length >= 65536)
        $header = pack('CCNN', $b1, 127, $length);
    return $header . $text;
}

//handshake new client.
function perform_handshaking($receved_header, $client_conn, $host, $port) {
    $headers = array();
    $lines = preg_split("/\r\n/", $receved_header);
    foreach ($lines as $line) {
        $line = chop($line);
        if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
            $headers[$matches[1]] = $matches[2];
        }
    }

    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
            "Upgrade: websocket\r\n" .
            "Connection: Upgrade\r\n" .
            "WebSocket-Origin: $host\r\n" .
            "WebSocket-Location: ws://$host:$port/demo/shout.php\r\n" .
            "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_conn, $upgrade, strlen($upgrade));
}
